package com.ruoyi.utils;

import com.ruoyi.config.StaticResourceConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@Slf4j
@Component
public class ImageFileUtil {

    private static StaticResourceConfig staticResourceConfig;
    public ImageFileUtil(){
        this.staticResourceConfig = new StaticResourceConfig();
    }

    /**
     * 读取图片文件为字节数组
     */
    public static byte[] readImageAsBytes(String imagePath) {
        try {
            Path fullPath = getImageFullPath(imagePath);
            String path = fullPath.toAbsolutePath().toString();
            log.info("图片路径2："+path);
            if (Files.exists(fullPath) && Files.isReadable(fullPath)) {
                return Files.readAllBytes(fullPath);
            } else {
                log.info("图片文件不存在或不可读: {}", fullPath);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("读取图片文件失败: {}", imagePath, e);
            return null;
        }
    }

    /**
     * 读取图片文件为Base64字符串
     */
    public static String readImageAsBase64(String imagePath) {
        byte[] imageBytes = readImageAsBytes(imagePath);
        if (imageBytes != null) {
            String extension = getFileExtension(imagePath);
            String base64Prefix = getBase64Prefix(extension);
            return base64Prefix + Base64.getEncoder().encodeToString(imageBytes);
        }
        return null;
    }

    /**
     * 读取图片文件为InputStream
     */
    public static InputStream readImageAsStream(String imagePath) {
        try {
            Path fullPath = getImageFullPath(imagePath);
            if (Files.exists(fullPath) && Files.isReadable(fullPath)) {
                return Files.newInputStream(fullPath);
            } else {
                log.warn("图片文件不存在或不可读: {}", fullPath);
                return null;
            }
        } catch (IOException e) {
            log.error("读取图片文件失败: {}", imagePath, e);
            return null;
        }
    }

    /**
     * 检查图片文件是否存在
     */
    public static boolean imageExists(String imagePath) {
        Path fullPath = getImageFullPath(imagePath);
        return Files.exists(fullPath) && Files.isReadable(fullPath);
    }

    /**
     * 获取图片文件信息
     */
    /*public ImageFileInfo getImageInfo(String imagePath) {
        try {
            Path fullPath = getImageFullPath(imagePath);
            if (Files.exists(fullPath)) {
                BasicFileAttributes attrs = Files.readAttributes(fullPath, BasicFileAttributes.class);
                String contentType = Files.probeContentType(fullPath);

                return ImageFileInfo.builder()
                        .fileName(fullPath.getFileName().toString())
                        .filePath(fullPath.toString())
                        .fileSize(attrs.size())
                        .lastModified(attrs.lastModifiedTime().toMillis())
                        .contentType(contentType)
                        .extension(getFileExtension(imagePath))
                        .build();
            }
        } catch (IOException e) {
            logger.error("获取图片信息失败: {}", imagePath, e);
        }
        return null;
    }*/

    /**
     * 获取图片的完整路径
     */
    private static Path getImageFullPath(String imagePath) {
        String rootPath = staticResourceConfig.getStaticRootPath();
        log.info("图片路径1："+rootPath);
        Path root = Paths.get(rootPath).toAbsolutePath().normalize();
        Path relativePath = Paths.get(imagePath).normalize();
        // 防止路径遍历攻击
        if (relativePath.startsWith("..") || relativePath.isAbsolute()) {
            throw new SecurityException("非法路径访问: " + imagePath);
        }

        return root.resolve(relativePath);
    }

    /**
     * 检查是否为图片文件
     */
    private static boolean isImageFile(Path path) {
        if (!Files.isRegularFile(path)) {
            return false;
        }
        String fileName = path.getFileName().toString().toLowerCase();
        return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
                || fileName.endsWith(".png") || fileName.endsWith(".gif")
                || fileName.endsWith(".bmp") || fileName.endsWith(".webp");
    }

    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex + 1).toLowerCase() : "";
    }

    /**
     * 获取Base64前缀
     */
    private static String getBase64Prefix(String extension) {
        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return "data:image/jpeg;base64,";
            case "png":
                return "data:image/png;base64,";
            case "gif":
                return "data:image/gif;base64,";
            case "bmp":
                return "data:image/bmp;base64,";
            case "webp":
                return "data:image/webp;base64,";
            default:
                return "data:image/jpeg;base64,";
        }
    }
}
